package com.jxud.service.impl;

import com.jxud.Pojo.*;
import com.jxud.mapper.ProductsMapper;
import com.jxud.service.ProductService;
import com.jxud.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class ProductServiceImpi implements ProductService {
    @Autowired
    private ProductsMapper productsMapper;

    /**
     * 商品查询 包含分页查询
     *
     * @param pageProduct
     * @return
     */
    @Override
    public Map<String, Object> getProducts(PageProduct pageProduct, HttpServletRequest request) {
        pageProduct.setOffset((pageProduct.getPage() - 1) * pageProduct.getSize());

        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJwt(token);
        String wxName = (String) claims.get("wxName");

        if ("admin".equals(wxName)) {
            List<Product> productsList = productsMapper.getAdminProducts(pageProduct);
            log.info("查询的商品的信息{}", productsList);

            int totalProducts = productsMapper.getTotalProduct(pageProduct);
            Map<String, Object> map = new HashMap<>();
            map.put("totalProducts", totalProducts);
            map.put("Product", pageProduct.getPage());
            map.put("Size", pageProduct.getSize());
            map.put("productsList", productsList);
            return map;

        } else {
            List<Products> productsList = productsMapper.getProducts(pageProduct);
            log.info("查询的商品的信息{}", productsList);

            int totalProducts = productsMapper.getTotalProduct(pageProduct);
            Map<String, Object> map = new HashMap<>();
            map.put("totalProducts", totalProducts);
            map.put("Product", pageProduct.getPage());
            map.put("Size", pageProduct.getSize());
            map.put("productsList", productsList);
            return map;
        }
    }

    /**
     * 创建新商品
     * @param product
     * @return
     */
    @Override
    @Transactional
    public String createProducts(Product product) {
        try{
            System.out.println("插入的商品信息---" + product);

            if (product.getTags() != null) {
                product.setTags(product.getTags()); // 触发 setter
            }
            if (product.getFaqs() != null) {
                product.setFaqs(product.getFaqs()); // 触发 setter
            }

            // 设置时间戳
            LocalDateTime now = LocalDateTime.now();
            product.setCreatedAt(now);
            product.setUpdatedAt(now);

            System.out.println("商品信息---" + product);
            Integer productsMapper1 = productsMapper.createProductsMapper(product);
            if (productsMapper1 > 0) {
                return "插入成功";
            }
            return "插入失败";
        }catch (Exception e){
            if (e.getMessage().contains("Duplicate entry")) {
                return "插入失败：产品编码重复";
            }
            return "插入失败：" + e.getMessage();
        }
    }

    /**
     * 获取商品表结构信息
     * @param tableName
     * @return
     */
    @Override
    public TableStructureResponse getTableStructure(String tableName) {
        TableStructureResponse response = new TableStructureResponse();
        response.setTableName(tableName);
        response.setTableComment(productsMapper.getTableComment(tableName));
        response.setColumns(productsMapper.getTableStructure(tableName));
        response.setGenerateTime(new Date());
        log.info("成功获取表 {} 的结构信息，共 {} 个字段",
                tableName, response.getColumns().size());
        return response;
    }

    /**
     * 获取/ 添加 系列表
     * @param request
     * @return
     */
    @Override
    public Result getClassify(ClassifyRequest request) {
        try {
            String name = request.getName();
            String id = request.getId();

            // 可选：非空校验
            if (id == null || id.trim().isEmpty()) {
                return Result.error("操作参数不能为空");
            }
            if ("0".equals(id)) {
                List<ClassifyRequest> brand = productsMapper.getBrand(name);
                Map<String, Object> map = new HashMap<>();
                map.put("brand", brand);
                return Result.success(map);
            } else if (name != null && !name.trim().isEmpty() && "1".equals(id)) {
                try{
                    int rows = productsMapper.insertBrand(name);
                    return Result.success(name + "插入成功");
                }catch (Exception e){
                    if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                        String message = e.getMessage();
                        if (message.contains("Duplicate entry") && message.contains("for key 'brand.name'")) {
                            log.warn("品牌名称已存在，无法重复添加：{}", name);
                            return Result.error("品牌名称【" + name + "】已存在，请勿重复添加");
                        }
                    }
                    log.error("添加品牌失败", e);
                    return Result.error("系统异常，添加品牌失败");
                }
            } else {
                    log.error("插入系列表参数id{}名称{}", id, name);
                    return Result.error("参数为空，请求失败");
                }
        } catch (Exception e) {
            log.error("获取系列表信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新商品表信息
     * @param product
     * @return
     */
    @Override
    public Boolean updateProducts(Product product) {

        if (product.getTags() != null) {
            product.setTags(product.getTags()); // 触发 setter
        }
        if (product.getFaqs() != null) {
            product.setFaqs(product.getFaqs()); // 触发 setter
        }

        // 设置时间戳
        LocalDateTime now = LocalDateTime.now();
        product.setUpdatedAt(now);
        Integer rows = productsMapper.insertProductsMapper(product);

        return rows > 0;
    }
}
